import fg from 'fast-glob';
import fs from 'fs-extra';
import path from 'path';
import { ICfg, TAction } from '../typings/index.js';
import { Record } from './Record.js';
import { getCurrentDir } from '../tools/esm.js';
import { toolchain } from '../toolchain.js';

export class Finder {

    public async execute(): Promise<void> {
        if (toolchain.opts.projectName) {
            const __dirname = getCurrentDir();

            Record.Instance.setRecordFile(path.join(__dirname, `../../record/${toolchain.opts.projectName}.txt`));

            // 读入配置
            const cfgFile = path.join(__dirname, `../../cfg/${toolchain.opts.projectName}.json`);
            if (!fs.existsSync(cfgFile)) {
                console.error('no cfg file:', cfgFile);
                process.exit(1);
            }
            const cfg = await fs.readJson(cfgFile) as ICfg;
            toolchain.opts.cfg = cfg;
        }

        if (toolchain.opts.action == 'all') {
            // // 删除没用的代码
            // await this.handleAction('stripeCode');
            // 删除没用的UI
            await this.handleAction('stripeUI');
            // 删除没用的材质球
            await this.handleAction('stripeMat');
            // 删除没用的fbx
            await this.handleAction('stripeFbx');
            // 删除没用的动画
            await this.handleAction('stripeAnim');
            // 删除没用的图片
            await this.handleAction('stripeImage');
            // 删除没用的图标
            await this.handleAction('stripeIcon');
            // 清除空文件夹
            await this.handleAction('treeShake');
            await this.handleAction('treeShake');
            await this.handleAction('treeShake');
        } else {
            await this.handleAction(toolchain.opts.action);
        }
    }

    private async handleAction(action: TAction): Promise<void> {
        if (action == 'delete') {
            // 删除文件
            toolchain.r.beginUse();
            const hasPrefab = await toolchain.handyman.executeDelete(toolchain.r);
            if (hasPrefab) {
                // 删除没用的.asset
                await this.handleAction('stripeAsset');
                // 删除没用的材质球
                await this.handleAction('stripeMat');
                // 删除没用的fbx
                await this.handleAction('stripeFbx');
                // 删除没用的动画
                await this.handleAction('stripeAnim');
                // 删除没用的图片
                await this.handleAction('stripeImage');
                // 删除空文件夹
                await this.handleAction('treeShake');
            }
            toolchain.r.stopUse();
        } else if (action == 'treeShake') {
            // 清除空文件夹
            await toolchain.treeShake.lookUp();
        } else if (action == 'findUsage') {
            // 查找引用
            if (toolchain.opts.input) {
                await toolchain.usageFinder.lookUp(toolchain.opts.input);
            }
        } else if (action == 'findImage') {
            await toolchain.imgFinder.findIt();
        } else if (action == 'replaceImage') {
            // 替换旧图
            await toolchain.imgReplacer.test();
        } else if (action == 'findLegacy') {
            // 查找旧文件
            await toolchain.legacyFinder.lookUp();
        } else if (action == 'usingLegacy') {
            // 查找旧文件引用
            await toolchain.usingLegacy.lookUp();
        } else if (action == 'findAlpha') {
            // 查找alpha为0的图片使用
            await toolchain.alphaImgFinder.lookUp();
        } else if (action == 'findDisabled') {
            // 查找没有激活的的图片
            await toolchain.disabledImgFinder.lookUp();
        } else if (action == 'cleanAtlas') {
            // 查看atlas文件夹内是否有非图片资源
            await toolchain.atlasCleaner.lookUp();
        } else if (action == 'statFileTypes') {
            // 关闭mipmap
            await toolchain.fileTypeScanner.go();
        } else if (action == 'disableMipMap') {
            // 关闭mipmap
            await this.turnOffMipMap();
        } else if (action == 'usedWhere') {
            // 查询指定文件被使用情况
        } else if (action == 'stripeCode') {
            // 删除没用的代码
            await toolchain.codeStriper.removeUseless();
        } else if (action == 'patchCode') {
            // 代码打补丁
            await toolchain.codePatcher.patchAny();
        } else if (action == 'organizeImports') {
            // 代码打补丁
            await toolchain.codePatcher.organizeImports();
        } else if (action == 'stripeUICode') {
            // 查找没用的UI代码
            await toolchain.codeStriper.findSuspectedUselessUI();
        } else if (action == 'codeHint') {
            // 给出代码优化提示
            await toolchain.codeStriper.showCodeHint();
        } else if (action == 'stripeMat') {
            // 删除没用的材质球
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.mat', toolchain.r, true);
        } else if (action == 'stripeFbx') {
            // 删除没用的fbx
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.fbx', toolchain.r, false);
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.FBX', toolchain.r, false);
        } else if (action == 'stripeAnim') {
            // 删除没用的动画
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.controller', toolchain.r, false);
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.anim', toolchain.r, false);
        } else if (action == 'stripeAsset') {
            // 删除没用的.asset
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.asset', toolchain.r, false);
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.bytes', toolchain.r, false);
            await toolchain.generateStriper.removeUseless(toolchain.opts, '.atlas.txt', toolchain.r, false);
        } else if (action == 'stripeFont') {
            // 删除没用的字体
            await toolchain.fontStriper.removeUseless();
        } else if (action == 'stripeJson') {
            // 删除没用的Json字段
            await toolchain.jsonStriper.removeUseless();
        } else if (action == 'checkJsonLiveness') {
            // 检查json冗余
            await toolchain.jsonStriper.checkLiveness();
        } else if (action == 'stripeProtocol') {
            // 删除没用的协议字段
            await toolchain.protocolStriper.removeUseless();
        } else if (action == 'stripeUI') {
            // 删除没用的UI
            await toolchain.uiStriper.removeUseless();
        } else if (action == 'fixPrefab') {
            // 删除prefab中的冗余节点
            await toolchain.prefabFixer.removeRedundantNodes();
        } else if (action == 'rmbtn') {
            const buttonCS = path.join(toolchain.opts.projectRoot, 'Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs');
            await toolchain.scriptStriper.removeScript(toolchain.opts, buttonCS);
        } else if (action == 'rmtranslator') {
            const translatorCS = path.join(toolchain.opts.projectRoot, 'Assets/Scripts/i18n/Translator.cs');
            await toolchain.scriptStriper.removeScript(toolchain.opts, translatorCS);
        } else if (action == 'stripeImage') {
            // 删除没用的图片
            await toolchain.imgStriper.removeUseless(toolchain.r);
        } else if (action == 'stripeIcon') {
            // 删除没用的icon
            await toolchain.iconStriper.removeUseless();
        } else if (action == 'npot') {
            // 修复NPOT图片
            await toolchain.npot.fixAll();
        } else if (action == 'readable') {
            // 修复isreadable
            await toolchain.imgReadable.fixAll();
        } else if (action == 'dedupImage') {
            // 图片去重
            await toolchain.imgDedup.execute();
        } else if (action == 'sortAtlas') {
            // 搜查大图片精灵
            await toolchain.imgSorter.sortAtlas();
        } else if (action == 'missing') {
            // 查找丢失
            await toolchain.missing.findMissing();
        } else if (action == 'checkI18N') {
            // 检查i18n
            await toolchain.i18nChecker.check();
        } else if (action == 'svnmv') {
            // svn mv
            await toolchain.svnmv.move();
        } else if (action == 'cutImage') {
            // cut image
            await toolchain.imgCutter.cut();
        } else if (action == 'syncCutImage') {
            // sync cut image
            await toolchain.imgCutter.syncFrom();
        } else if (action == 'sortTmpMat') {
            await toolchain.tmpMatSorter.start();
        } else if (action == 'replace') {
            await toolchain.handyman.replaceFile();
        } else if (action == 'checkTextFormat') {
            await toolchain.textFormatChecker.check();
        } else if (action == 'anyway') {
            await toolchain.handyman.anyway();
        } else {
            console.error('Action not supported!', action);
        }
    }

    private async turnOffMipMap(): Promise<void> {
        const metas = await fg('**/*.meta', { cwd: toolchain.opts.projectRoot });
        console.log('total metas:', metas.length);
        for (const mt of metas) {
            if (!mt.includes('Lightmap')) {
                const file = path.join(toolchain.opts.projectRoot, mt);
                const content = await fs.readFile(file, 'utf-8');
                if (content.includes('enableMipMap: 1')) {
                    const newContent = content.replace('enableMipMap: 1', 'enableMipMap: 0');
                    await fs.writeFile(file, newContent, 'utf-8');
                }
            }
        }

    }
}
